package com.ncloud.chnl.service.impl;


import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ncloud.aaaa.service.RoleService;
import com.ncloud.aaaa.service.UserService;
import com.ncloud.chnl.entity.Sale;
import com.ncloud.chnl.mapper.SaleMapper;
import com.ncloud.chnl.service.SaleService;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.common.utils.PageHelperUtils;
import com.ncloud.param.service.SequenceService;

@Service
public class SaleServiceImpl implements SaleService {
	
	private static final Logger logger = LogManager.getLogger(SaleServiceImpl.class);

	@Autowired
	private SaleMapper saleMapper;
	@Reference
	private SequenceService sequence;
	@Reference
	private UserService userService;
	@Reference
	private RoleService roleService;

	@Override
	public JSONObject modifySale(JSONObject json) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public JSONObject deleteSale(JSONObject json) {
		Long saleId = json.getLong("saleId");
		JSONObject jsonInfo = new JSONObject();
		int info = 0;
		try {
			info =saleMapper.deleteSale(saleId);
			jsonInfo.put("coke",info);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
			return jsonInfo;
	}
	
	@Override
	public JSONObject getSale(JSONObject json) {
		JSONObject result = new JSONObject();
		Long userId = json.getLong("userID");
		if(userId!=null){
			try {
				String chnl_name = saleMapper.getChnlName(userId);		
				Sale sale = saleMapper.getSale(userId);
				result.put("saleId", sale.getSaleId());
				result.put("chnlID",sale.getChnlId() );
				result.put("userId",sale.getUserId() );
				result.put("jobTitle",sale.getJobTitle() );
				result.put("remark",sale.getRemark() );
				result.put("chnl_name", chnl_name);
		
			} catch (Exception e) {
				e.printStackTrace();
				result.put("recode", "00000");
				result.put("recodeMsg", "查询失败");
			}
		}else{
			result.put("recode", "00000");
			result.put("recodeMsg", "userid不能为空");
		}
		return result;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object getChnlSales(JSONObject json) {
		if(!json.containsKey("chnlId")){
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		Long chnlId = json.getLong("chnlId");
		Object object = null;
		PageInfo pageInfo = null;
		if(PageHelperUtils.isPage(json)){
			PageHelperUtils.setPageParam(json);
			List<Map<String, Object>> sales = saleMapper.getChnlSales(chnlId);
			pageInfo = new PageInfo(sales);
			object = JSON.parseObject(JSON.toJSONString(pageInfo));
		}else {
			List<Map<String, Object>> sales = saleMapper.getChnlSales(chnlId);
			object = JSON.parseArray(JSON.toJSONString(sales));
		}
		
		return object;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object getAllChnlSales(JSONObject json) {
		Long userId = json.getLong("userID");
		Object object = null;
		PageInfo pageInfo = null;
		if(PageHelperUtils.isPage(json)){
			PageHelperUtils.setPageParam(json);
			List<Map<String, Object>> sales = saleMapper.getAllChnlSales(userId);
			pageInfo = new PageInfo(sales);
			object = JSON.parseObject(JSON.toJSONString(pageInfo));
		}else {
			List<Map<String, Object>> sales = saleMapper.getAllChnlSales(userId);
			object = JSON.parseArray(JSON.toJSONString(sales));
		}
		
		return object;
	}

	@Override
	public JSONObject insertSale(JSONObject json) {
		Sale sale = JSON.parseObject(json.toJSONString(),Sale.class);
		int info = 0;
		JSONObject jsonInfo = new JSONObject();
		try {
			Long saleId = sequence.getSequence("SALE_ID_SEQ");
			sale.setSaleId(saleId);
			info =saleMapper.insertSale(sale);
			jsonInfo.put("coke", info);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
			return jsonInfo;
	}

	@Override
	public JSONObject updateSale(JSONObject json) {
		
		Sale saleInfo = new Sale();
		JSONObject jsonInfo = new JSONObject();
		Long saleId = json.getLong("saleId");
		if(saleId == null){
			throw new UserException();
		}else{			
			saleInfo = saleMapper.getSaleBySaleId(saleId);			
		}		
		if(json.containsKey("chnlId")){
			Long chnlId = json.getLong("chnlId");
			saleInfo.setChnlId(chnlId);
		}
		if(json.containsKey("userId")){
			Long userId = json.getLong("userId");
			saleInfo.setUserId(userId);
		}
		if(json.containsKey("jobTitle")){
			String jobTitle = json.getString("jobTitle");
			saleInfo.setJobTitle(jobTitle);
		}
		if(json.containsKey("remark")){
			String remark = json.getString("remark");
			saleInfo.setRemark(remark);
		}
				
		int info = 0;
		try {
			info =saleMapper.updateSale(saleInfo);
			jsonInfo.put("coke",info);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
			return jsonInfo;
	}

	@Override
	public Object setGroupManager(JSONObject json) {
		// 校验入参
//		Long userID = json.getLong("userID");
		if(json.containsKey("userId") && json.getLong("userId")!=null){
			Long userId = json.getLong("userId");
			dealUserRole(userId);
		}else if(json.containsKey("userList") && json.getJSONArray("userList").size()>0){
			JSONArray array = json.getJSONArray("userList");
			for (Object object : array) {
				Long userId = (Long )object;
				dealUserRole(userId);
			}
		}else{
			throw new UserException(ResultEnum.PARAM_ERROR);
		}
		
		return HttpStatus.OK;
	}

	private void dealUserRole(Long userId) {
		try {
			// 更新sale表中的jobTitle
			Sale sale = saleMapper.getSale(userId);
			sale.setJobTitle("1");
			saleMapper.updateSale(sale);
			// 更新roleuser表中记录
			JSONObject userRole = new JSONObject();
			userRole.put("userId", userId);
			userRole.put("roleId", "2");
			roleService.updateUserRole(userRole);
		} catch (Exception e) {
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
	}
}
